<?php

/**
 * Created by Sublime.
 * User: tchenym
 * Date: 2018/08/21
 * Time: 上午午10:25
 */
class Cart_model extends CI_Model
{

    public function __construct()
    {
        $this->load->database();
        $this->load->helper("common");
        $this->load->model('customer_model');
    }

    //购物车添加、减少数量
    public function changeCartNum($param)
    {
        $user_id = $this->customer_model->sessionKeyToUserId($param['session_key']);
        $where   = array('shop_id' => $param['shop_id'], 'user_id' => $user_id, 'goods_id' => $param['goods_id'], 'type' => 2);
        if ($param['type'] == 1) {
            $row = $this->db->where($where)->from('app_cart')->get()->row_array();
            if ($row) {
                $res = $this->db->where($where)->set('num', 'num+1', false)->update('app_cart');
            } else {
                $data             = array();
                $data['user_id']  = $user_id;
                $data['shop_id']  = $param['shop_id'];
                $data['goods_id'] = $param['goods_id'];
                $data['type']     = 2;
                $data['num']      = 1;
                $res              = $this->db->insert('app_cart', $data);
            }
        } elseif ($param['type'] == 2) {
            $res = $this->db->where($where)->set('num', 'num-1', false)->update('app_cart');
        } else {
            $res = $this->db->where($where)->update('app_cart', array('num' => $param['num']));
        }
        if ($res) {
            return $res;
        } else {
            return false;
        }
    }

    //删除购物车
    public function delCartNum($param)
    {
        $user_id = $this->customer_model->sessionKeyToUserId($param['session_key']);
        $where   = array('goods_id' => $param['goods_id'], 'user_id' => $user_id);
        $res     = $this->db->where($where)->delete('app_cart');
        if ($res) {
            return $res;
        } else {
            return false;
        }
    }
}
